﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using log4net;

namespace NFit.Core
{
    /// <summary>
    /// Default implementation of the fixture catalog
    /// </summary>
    public class DefaultFixtureCatalog : IFixtureCatalog
    {
        private static ILog logger = log4net.LogManager.GetLogger(typeof(DefaultFixtureCatalog));
        private Dictionary<string, Type> FixtureCatalog = new Dictionary<string, Type>();

        /// <summary>
        /// Constructor
        /// </summary>
        public DefaultFixtureCatalog()
        {
            LoadFixtureCatalog();
        }

        /// <summary>
        /// Get the type of the object given it's class name
        /// </summary>
        /// <param name="fixturename"></param>
        /// <returns></returns>
        public Type GetFixture(string fixturename)
        {
            if (FixtureCatalog.ContainsKey(fixturename))
            {
                return FixtureCatalog[fixturename];
            }
            return null;
        }

        private void LoadFixtureCatalog()
        {
            Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();

            foreach (var ass in assemblies)
            {
                try
                {
                    Type[] types = ass.GetTypes();
                    foreach (var type in types)
                    {
                        if (type.IsAFixtureImplementation())
                        {
                            FixtureCatalog.Add(type.Name, type);
                        }
                        if (type.IsATestImplementation())
                        {
                            FixtureCatalog.Add(type.Name, type);
                        }
                    }
                }
                catch (Exception ex)
                {          
                    logger.Warn("Fixture Catalog error", ex);
                }
            }
        }
    }
}
